import { asyncRoutes, routes as staticRoutes } from "@/router"


function hasPromission(roles, route) {
    if (route.meta && route.meta.roles) {
        if (route.meta.roles == roles) {
            return true
        }else {
            return false
        }
    }else {
        return true
    }
}

function filterAsyncRoutes(roles, routes) {
    const res = [];

    routes.some(route => {
        const tmp = { ...route }
        if (hasPromission(roles, tmp)) {
            if (tmp.children && tmp.children.length > 1) {
                tmp.children = filterAsyncRoutes(roles, tmp.children)
            }
            res.push(tmp)
        }
    })
    return res
}

const state = {
    routes: [],
    addRoutes: []
}

const mutations = {
    SET_ROUTES: (state, routesArr) => {
        state.addRoutes = routesArr;
        state.routes = staticRoutes.concat(routesArr)
    },
    removeRoutes: (state) => {
        state.routes = []
    }
}

const actions = {
    generatorRoutes: ({ commit }, roles) => {
        let routes;
        return new Promise(resolve => {
            routes = filterAsyncRoutes(roles, asyncRoutes)
            commit("SET_ROUTES", routes)
            resolve(routes)
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}